#!/usr/bin/python3
import sys
import threading
import time
import datetime
import csv
from uart import Uart
from humiture import Humiture
from net import mySocket
from tisscmd import tissCmd
from net import *
from Protocol import *
# from humiture import *
from zhongsheng import *
from youyunhy import *

humit = []
peakPower = [0, 0]
sampleSlot = 1
recivedDataFlag = 0
# last_temp = 0
stabilizeFlag = True
filename = ""
stabilizeCoefficient = 0
tempList = [0]
reciverThzDataSignal = threading.Condition()
threadLock = threading.Lock()

def humitureHandler(addr, data):
    global humit

    humit.clear()
    res = humt.handler(data)

    if res and res[0] == 1:
        humit += res[1:]
        print(humit)
        csvAppend(humit)


def UartHumitureHandler(data):
    global humit
    global recivedDataFlag
    
    humit.clear()
    res = humt.handler(data)

    if res and res[0] == 1:
        humit += res[1:]
        print(humit)
        csvAppend(humit)

def netTimeoutHandler(sokit: socket):
    pass
    sokit.close()

# 获取温湿度
def getData():
    global recivedDataFlag
    recivedDataFlag = 0
    getDataThread()
    humt.humitureRead()

def getDataThread():
    threading.Timer(sampleSlot, getData).start()

def csvAppend(data):
    tmp = ",".join(map(str, data))
    rowData = []
    rowData.append(datetime.datetime.now().strftime("\'%Y%m%d%H%M%S"))
    rowData += tmp.split(",")
    # 以写方式打开文件。注意添加 newline=""，否则会在两行数据之间都插入一行空白。
    with open(filename, mode="a", encoding="utf-8-sig", newline="") as recordFile:
        # 基于打开的文件，创建 csv.writer 实例
        writer = csv.writer(recordFile)
        # writerow() 一次只能写入一行。
        writer.writerow(rowData)

def checkDataFullThread():
    data = []
    global peakPower
    global recivedDataFlag

    with reciverThzDataSignal:
        while True:
            reciverThzDataSignal.wait()
            threadLock.acquire()
            flag = recivedDataFlag

            threadLock.release()
            print("flag = 0x%x" % flag)
            if flag == 0x07:
                data.append(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
                data += peakPower
                data += humit
                csvAppend(data)
                data.clear()
                humit.clear()
                peakPower[0] = None
                peakPower[1] = None
                recivedDataFlag = 0


def wait_for_data_stabilize(temp):
    global filename
    global stabilizeFlag
    global stabilizeCoefficient
    global tempList

    tempDelta = abs(temp - tempList[0])
    if stabilizeFlag and tempDelta >= 0.5:
        stabilizeFlag = False

        filename = "./data/humiture-%2.2f-%s.csv" % (
            temp,
            time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime()),
        )
        if not os.path.exists('./data'):
            os.mkdir('./data')
        rowData = ["Time", "168:THZ", "169:THZ", "TMPERATURE", "HUMITIDY"]
        with open(filename, mode="w", encoding="utf-8-sig", newline="") as f_out:
            # 基于打开的文件，创建 csv.writer 实例
            writer = csv.writer(f_out)
            writer.writerow(rowData)
    elif tempDelta < 0.5:
        stabilizeCoefficient += 1
        if stabilizeCoefficient > 10:
            stabilizeFlag = True
    else:
        stabilizeCoefficient = 0
        stabilizeFlag = False
        tempList.clear()

    if len(tempList) == 10:
        tempList.pop(0)
    tempList.append(temp)


if __name__ == "__main__":
    if len(sys.argv) != 1:
        sampleSlot = sys.argv[1]  # 获取采样间隔
# 通过网络来读取
    # humt = Zhongsheng(2)
    # humtSokit = mySocket("192.168.3.80", 10123, humitureHandler)
    # humtSokit.startRecv()
    # humt.tranmiteMethodRegistor(humtSokit.sendList)
# 通过串口读取
    # humt = Zhongsheng(1)
    humt = Youyun(1)
    humUart = Uart("/dev/ttyPS1", 115200, 8, 1, "NONE", UartHumitureHandler)
    humUart.serialOn()
    humt.tranmiteMethodRegistor(humUart.sendData)

    threading.Thread(target=checkDataFullThread).start()
    getData()

    target = '/home/tjkj/work/temperature/data/'
    filename = "humiture-%s.csv" % (
        time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime()),
    )
    if not os.path.exists(target):
        os.mkdir(target)
    rowData = ["Time", "TMPERATURE", "HUMITIDY"]
    with open(filename, mode="w", encoding="utf-8-sig", newline="") as f_out:
        # 基于打开的文件，创建 csv.writer 实例
        writer = csv.writer(f_out)
        writer.writerow(rowData)
